using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using CoachingOrganizer.Logic.Models.Common;
using CoachingOrganizer.iOS.Decorators;
using CoachingOrganizer.Logic.Models.Tools;
using CoachingOrganizer.Logic.Models.Tools.MoodLevel;
using CoachingOrganizer.Logic.Models.Tools.EmotionsPack;
using CoachingOrganizer.iOS.Controllers.Tools.MoodLevel;
using CoachingOrganizer.iOS.Controllers.Tools.EmotionsPack;
using CoachingOrganizer.Logic.Models.Tools.MoneyCalculation;
using CoachingOrganizer.iOS.Controllers.Tools.MoneyCalculation;
using CoachingOrganizer.iOS.Controllers;
using CoachingOrganizer.iOS.Helpers;

namespace CoachingOrganizer.iOS.DataSources
{
    public class ToolsDataSource : UITableViewSource
    {
        public const string CellIdentifer = "ToolCell";

        private readonly UITableView _view;
        private readonly SupplyGoalDetailsViewController _controller;
        private readonly GoalModel _model;
        private readonly SimpleTableDataSourceDecorator<UIViewController, ToolModelBase> _tableCellsSource;

        public ToolsDataSource(UITableView view, SupplyGoalDetailsViewController controller, GoalModel model)
        {
            _view = view;
            _controller = controller;
            _model = model;
            _tableCellsSource = new SimpleTableDataSourceDecorator<UIViewController, ToolModelBase>(CellIdentifer, _view, _controller, p => _model.Tools.ElementAtOrDefault(p.Row), m => GetCellController(m));
            model.ToolsChanged += Model_ToolsChanged;
            model.ToolsCollectionChanged += Model_ToolsCollectionChanged;
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            return _tableCellsSource.GetCell(indexPath);
        }

        public override int RowsInSection(UITableView tableview, int section)
        {
            return UIHelper.GetCollectionItemsCount(_model.Tools);
        }

        private UIViewController GetCellController(ToolModelBase tool)
        {
            if (tool is MoodLevelModel)
                return new MoodLevelViewController((MoodLevelModel)tool);
            if (tool is EmotionsPackModel)
                return new EmotionsPackViewController((EmotionsPackModel)tool);
            if (tool is MoneyCalculationModel)
                return new MoneyCalculationViewController((MoneyCalculationModel)tool);
            throw new NotImplementedException();
        }

        private void Model_ToolsChanged(object sender, EventArgs e)
        {
            _tableCellsSource.ProceedCollectionReplaced();
        }

        private void Model_ToolsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            _tableCellsSource.ProceedCollectionChanged(e);
        }
    }
}